Note that the name of tkinter changed from "Tkinter" in Python 2.x to "tkinter" in Python 3.x.
A regular problem that will arise in Python programs is getting values from the user. The code below will display a dialog box and ask the user to enter a value. The value is then printed to "Debug I/O" but it could also be set to a global and then used later in the program. The dialog has been placed into a class to keep the code organized. This is a good practice and you can save the class to a module and use it in different Python programs you create. Try this code now and play around with changing the names of the labels and buttons.
from tkinter import * class MyDialog: def __init__(self, master): # called when the object is created self.WindowFrame = Toplevel(master) # get the window "frame" Label(self.WindowFrame, text="Value").pack() # add the label to the frame self.TheValue = Entry(self.WindowFrame) # add the text entry box for the value self.TheValue.pack(padx=5) OKButton=Button(self.WindowFrame, text="OK", command=self.OKPressed) # add the "OK" button OKButton.pack(pady=5) def OKPressed(self): # Called when the "OK" button is pressed print("Value inside MyDialog is "+self.TheValue.get()) # print the value self.ReturnedValue=self.TheValue.get() # the control will be destroyed with the window so we need to save it here. self.WindowFrame.destroy() # Close the parent
Then, use the code below to open the dialog and get a value from the user. Note that the code below uses "wait_window" to keep the user from interacting with other windows until they click "OK" and "destroy" this window. This makes the dialog "modal".
from tkinter import * import Mydialog MainWindow = Tk() # Get the MasterWindow object for Tkinter MainWindow.withdraw() # Don't show the modeless main window TheDialog=Mydialog.MyDialog(MainWindow) # Create the Dialog Box MainWindow.wait_window(TheDialog.WindowFrame) # Wait until the window is closed print("Value after returning from MyDialog: "+format(TheDialog.ReturnedValue))
Python Documentation: Classes
© Copyright 2018 HSU - All rights reserved.